package game.data;

import game.worlds.GameRole;
import game.buff.Buff;

/**
 * BUFF效果
 */
class BuffData {
	/**
	 * 角色
	 */
	public var role:GameRole;

	/**
	 * BUFF列表
	 */
	public var buffs:Array<Buff> = [];

	public function new() {}

	/**
	 * 添加BUFF
	 * @param buff 
	 */
	public function addBuff(buff:Buff):Void {
		if (buff.canOverride) {
			removeBuff(buff.id);
		} else if (hasBuff(buff.id))
			return;
		buff.role = role;
		buff.onInit();
		this.buffs.push(buff);
		trace("追加BUFF:", buff.id);
	}

	/**
	 * 根据ID获得BUFF，请注意BUFF可能为`null`。
	 * @param id 
	 * @return Buff
	 */
	public function getBuff(id:String):Buff {
		for (i in 0...this.buffs.length) {
			if (this.buffs[i].id == id) {
				return this.buffs[i];
			}
		}
		return null;
	}

	/**
	 * 删除BUFF
	 * @param id 
	 */
	public function removeBuff(id:String):Void {
		for (i in 0...this.buffs.length) {
			if (this.buffs[i].id == id) {
				this.buffs[i].onClean();
				this.buffs.splice(i, 1);
				return;
			}
		}
	}

	/**
	 * 特效是否存在
	 * @param id 
	 * @return Bool
	 */
	public function hasBuff(id:String):Bool {
		for (i in 0...this.buffs.length) {
			if (this.buffs[i].id == id) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 更新BUFF
	 * @param dt 
	 */
	private function update(dt:Float):Void {
		var readyRemove = [];
		for (buff in this.buffs) {
			buff.onUpdate(dt);
			if (buff.liveTime <= 0) {
				readyRemove.push(buff);
			}
		}
		for (buff in readyRemove) {
			this.removeBuff(buff.id);
		}
	}

	/**
	 * 释放所有BUFF
	 */
	public function dispose():Void {
		for (i in 0...this.buffs.length) {
			this.buffs[i].onClean();
		}
		this.buffs.splice(0, this.buffs.length);
	}
}
